package com.example.administrator.szb.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.base.BasePresenter;
import com.example.administrator.szb.activity.base.MVPBaseActivity;
import com.example.administrator.szb.activity.layout.RZActivity;
import com.example.administrator.szb.activity.layout.RZCenterActivity2;
import com.example.administrator.szb.bean.UserInfo3;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.http.OnResultListener;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.ChangeStatuUtil;
import com.example.administrator.szb.util.PhotoUtils;
import com.example.administrator.szb.util.QTLog;
import com.example.administrator.szb.util.SPUtils;
import com.example.administrator.szb.util.Toasts;
import com.example.zhouwei.library.CustomPopWindow;
import com.jph.takephoto.model.TResult;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import static com.example.administrator.szb.util.DialogUtil.popWindow;

public class MyInfoActivity extends MVPBaseActivity implements View.OnClickListener{
    private int type=0;//0普通用户   1顾问
    private LinearLayout head_img_ll;
    private de.hdodenhof.circleimageview.CircleImageView head_img;
    private LinearLayout nick_name_ll;
    private TextView nick_name;
    private View lines;
    private LinearLayout qian_name_ll;
    private TextView qian_name,bar_title;
    private LinearLayout phone_ll;
    private LinearLayout status_rz_ll;
    private TextView status_rz;
    private LinearLayout emails_ll;
    private TextView emails;
    private int status=1;//状态1 未认证 2待审核 3审核通过 4 未通过 5禁用
    String path="";
    public static boolean isNeedRefresh = false;
    private UserInfo3 userInfo3=null;
    PhotoUtils photoUtils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_info);
        bar_title = findViewById(R.id.bar_title);
        bar_title.setText("个人信息");
        photoUtils = new PhotoUtils();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView() {
        head_img_ll = (LinearLayout) findViewById(R.id.head_img_ll);
        head_img = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.head_img);
        nick_name_ll = (LinearLayout) findViewById(R.id.nick_name_ll);
        nick_name = (TextView) findViewById(R.id.nick_name);
        qian_name_ll = (LinearLayout) findViewById(R.id.qian_name_ll);
        qian_name = (TextView) findViewById(R.id.qian_name);
        phone_ll = (LinearLayout) findViewById(R.id.phone_ll);
        status_rz_ll = (LinearLayout) findViewById(R.id.status_rz_ll);
        status_rz = (TextView) findViewById(R.id.status_rz);
        emails_ll = (LinearLayout) findViewById(R.id.emails_ll);
        emails = (TextView) findViewById(R.id.emails);
        lines = findViewById(R.id.lines);
    }

    @Override
    protected void initEvent() {
        head_img_ll.setOnClickListener(this);
        nick_name_ll.setOnClickListener(this);
        qian_name_ll.setOnClickListener(this);
        phone_ll.setOnClickListener(this);
        status_rz_ll.setOnClickListener(this);
        emails_ll.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        type = getIntent().getIntExtra("type",0);
        status = getIntent().getIntExtra("status",1);
        if (type==1){
            lines.setVisibility(View.GONE);
            head_img_ll.setVisibility(View.GONE);
            qian_name_ll.setVisibility(View.GONE);
        }
        requestUserInfo();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedRefresh){
            requestUserInfo();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onClick(View v) {

        Intent intent;//type:所需要修改类型1呢称、2邮箱、3个性签名、4手机号5用户头像
        switch (v.getId()){
            case R.id.head_img_ll:
                showPopupwindow(R.layout.view_popupwindow_picture_choose, R.layout.activity_my_info);
                break;
            case R.id.nick_name_ll:
                intent = new Intent(context,MyInfoEditActivity.class);
                intent.putExtra("type",1);
                startActivity(intent);
                break;
            case R.id.qian_name_ll:
                intent = new Intent(context,MyInfoEditActivity.class);
                intent.putExtra("type",3);
                startActivity(intent);
                break;
            case R.id.phone_ll:
                /*if (userInfo3==null){
                    Toasts.show(context,"数据异常",1000);
                    rern;
                }*/
                if (TextUtils.isEmpty(SPUtils.getDatasString(SPUtils.USER_PHONE))){
                    Toasts.show(context,"数据异常",1000);
                    return;
                }
                intent = new Intent(context,MyInfoEditActivity.class);
                intent.putExtra("type",4);
                intent.putExtra("phone",SPUtils.getDatasString(SPUtils.USER_PHONE));
                startActivity(intent);
                break;
            case R.id.status_rz_ll:
                if (type==1){
                    intent = new Intent(context, RZCenterActivity2.class);
                    intent.putExtra("rzStatu",status);
                    startActivity(intent);
                }else {
                    startActivity(new Intent(context, RZActivity.class));
                }
                break;
            case R.id.emails_ll:
                intent = new Intent(context,MyInfoEditActivity.class);
                intent.putExtra("type",2);
                startActivity(intent);
                break;
        }
    }
    private void requestUserInfo(){
        //user_message
        Map<String,Object> params = new HashMap<>();
        params.put("code", HttpUtil.getParam());
        params.put("id", SPUtils.getUserId());
        HttpUtils.post(activity,URLAddress.URLBASE+URLAddress.GET_USER_INFO, params, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {
                isNeedRefresh = false;
                 userInfo3 = JSON.parseObject(str,new TypeReference<UserInfo3>(){});
                initUser(userInfo3);
            }

            @Override
            public void onFailure(int requestCode, String str) {

            }
        });
    }
    private void initUser(UserInfo3 userInfo3){
        Glide.with(context).load(userInfo3.getHeadimg()).error(R.mipmap.default_header_s).into(head_img);

        if (userInfo3.getNick_name()!=null){
            nick_name.setText(userInfo3.getNick_name());
        }
        if (userInfo3.getEmail()!=null){
            emails.setText(userInfo3.getEmail());
        }
        if (userInfo3.getStatus()!=null){
            status_rz.setText(userInfo3.getStatus());
        }
        if (userInfo3.getSketch()!=null){
            qian_name.setText(userInfo3.getSketch());
        }
    }

















    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void showPopupwindow(int view_layout_id, int rootview_layout_id) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);
        View rootview = LayoutInflater.from(this).inflate(rootview_layout_id, null);
        popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) //设置显示的大小，不设置就默认包裹内容
                .setFocusable(true)//是否获取焦点，默认为ture
                .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                .create()//创建PopupWindow
                .showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        handleLogic(popwindow_view, popWindow);//处理popupwindow 中的item点击事件

    }

    /**
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView, final CustomPopWindow mCustomPopWindow) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
                String showContent = "";
                switch (v.getId()) {
                    case R.id.textView26:
                        photoUtils.onClick(0,getTakePhoto());
                        break;
                    case R.id.textView27:
                        photoUtils.onClick(1,getTakePhoto());
                        break;
                    case R.id.textView28:
                        mCustomPopWindow.dissmiss();
                        break;
                }
                //Toasts.show(MingPianActivity.this, showContent, Toast.LENGTH_SHORT);
            }
        };
        contentView.findViewById(R.id.textView26).setOnClickListener(listener);
        contentView.findViewById(R.id.textView27).setOnClickListener(listener);
        contentView.findViewById(R.id.textView28).setOnClickListener(listener);
    }

    /**
     * 拍照或者从相片选取相片的回调方法
     *
     * @param result
     */
    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
         path = result.getImage().getOriginalPath();
        QTLog.e(path);
        Glide.with(this).load(new File(path)).into(head_img);
        requestUpdate();
    }
    //ChangeStatuUtil.bitmapToString(path)
    private void requestUpdate(){
        if (path==null){
            return;
        }

        Map<String,Object> params = new HashMap<>();
        params.put("code", HttpUtil.getParam());
        params.put("users_id", SPUtils.getUserId());
        params.put("content",ChangeStatuUtil.bitmapToString(path));
        params.put("type",5);
        HttpUtils.post(activity,URLAddress.URLBASE + URLAddress.EDIT_USER_INFO, params, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {
                Toasts.show(context,str,1000);
                requestUserInfo();
            }

            @Override
            public void onFailure(int requestCode, String str) {
                Toasts.show(context,"上传头像失败",1000);
            }
        });
    }

    /**
     * 返回一个Uri给take调用
     */
    public Uri getImageUri() {
        File file = getImgFile();
        return Uri.fromFile(file);

    }

    /**
     * 设置文件存储路径，返回一个file
     *
     * @return
     */
    private File getImgFile() {
        File file = new File(Environment.getExternalStorageDirectory() + "/szb/image");
        if (!file.exists()) {
            //要点！
            file.mkdirs();
        }
        File imgFile = new File(file, "image" + System.currentTimeMillis() + ".jpg");
        return imgFile;

    }
}
